package rt2

import (
	"fmt"

	"gitee.com/copperxcx/res"
	"github.com/sirupsen/logrus"
)

type ClientManager struct {
	server  *MultiCastServer
	clients map[string]*ClientHandler
}

func NewClientManager(ip string, port int) *ClientManager {

	mgr := &ClientManager{
		clients: make(map[string]*ClientHandler),
		server:  &MultiCastServer{},
	}
	ch, err := mgr.server.Start(ip, port)
	if err != nil {
		logrus.Error(err)
		return nil
	}
	go mgr.proc(ch)
	return mgr
}

func (m *ClientManager) proc(ch <-chan MultiCastClient) {
	for c := range ch {
		cc, ok := m.clients[c.Name]
		if ok {
			logrus.Errorf("client %s already exists! %v\n", c.Name, cc)
		}
		h := NewClientHandler(&c, false)
		m.clients[c.Name] = h
		// TODO 载入配置数据
	}
}

func (m *ClientManager) GetClient(name string) (*ClientHandler, bool) {
	cli, err := m.clients[name]
	return cli, err
}

func (m *ClientManager) HasClient(name string) bool {
	_, ok := m.clients[name]
	return ok
}

func ManagerGetRes[T res.ScalarType](m *ClientManager, name string, key string) (t T, err error) {
	cli, ok := m.GetClient(name)
	if !ok {
		return t, fmt.Errorf("client %s not found", name)
	}
	return HandlerGetRes[T](cli, key)
}

func ManagerSetRes[T res.ScalarType](m *ClientManager, name string, key string, value T) error {
	cli, ok := m.GetClient(name)
	if !ok {
		return fmt.Errorf("client %s not found", name)
	}
	return HandlerSetRes(cli, key, value)
}
